package utils

import (
	"github.com/golang-jwt/jwt/v5"
	"go-vue-blog-sever/config"
	"go-vue-blog-sever/gla"
	"time"
)

var (
	jwtKey = []byte("个人博客")
)

func NewToken(id int, name string, pwd string) (token string, err error) {
	claims := jwt.NewWithClaims(jwt.SigningMethodHS256, config.UserJwt{
		ID:       id,
		Name:     name,
		Password: pwd,
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    "zth",
			Subject:   "blog",
			Audience:  nil,
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(gla.Day)),
			NotBefore: nil,
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			ID:        "1201",
		},
	})
	return claims.SignedString(jwtKey)
}

func DecodeToken(tokenString string) (id int, name, password string, err error) {
	claims, err := jwt.ParseWithClaims(tokenString, &config.UserJwt{}, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})
	if err != nil {
		return 0, "", "", err
	}
	if c, ok := claims.Claims.(*config.UserJwt); ok {
		return c.ID, c.Name, c.Password, nil
	}
	return 0, "", "", nil
}
